package org.gruposp2p.proyectokarma.gwt.client.util;

import org.gruposp2p.proyectokarma.gwt.client.domain.SessionData;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;

public class RequestHelper {

    public static void doPost(String url, String postData, 
    		RequestCallback requestCallback) {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
        builder.setHeader("Content-Type", "application/json");
        Log.debug("doPost - url:" + url + " - postData:" + postData);
        try {
            Request response = builder.sendRequest(postData, requestCallback);
        } catch (RequestException e) {
            Log.error(e.getMessage(), e);
        }
    }

    public static void doGet(String url, 
    		RequestCallback requestCallback) {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        builder.setHeader("Content-Type", "application/json");
        Log.debug("doGet - url: " + url);
        try {
            Request response = builder.sendRequest("", requestCallback);
        } catch (RequestException e) {
            Log.error(e.getMessage(), e);
        }
    }

    public static void doPut(
            String url, String putData, RequestCallback requestCallback) {
        Log.debug("doPut - url: " + url + " - data: " + putData);
        RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT, url);
        builder.setHeader("Content-Type", "application/json");
        try {
            Request response = builder.sendRequest(putData, requestCallback);
        } catch (RequestException e) {
            Log.error(e.getMessage(), e);
        }
    }

    public static void doDelete(String url, RequestCallback requestCallback) {
        Log.debug("doDelete - url: " + url);
        RequestBuilder builder = new RequestBuilder(RequestBuilder.DELETE, url);
        builder.setHeader("Content-Type", "application/json");
        try {
            Request response = builder.sendRequest("", requestCallback);
        } catch (RequestException e) {
            Log.error(e.getMessage(), e);
        }
    }
    
    public static void submitForm(String url, String requestData, 
    		RequestCallback requestCallback) {
	    Log.debug("submitForm requestData: " + requestData + 
	    		" -url: " + url);
		RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url);
		requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded");
		requestBuilder.setRequestData(requestData);
	    requestBuilder.setCallback(requestCallback);
	    try {
	    	requestBuilder.send();
	    } catch (RequestException re) {
	    	Log.error(re.getMessage(), re);
    	}
    }

}
